import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Image, Text, Button } from '@tarojs/components'
import { getPlatformGoodsDetails, getJihuasuanStoreCanOrder } from '@/api/goods/details'
import { getSkuInfo, createCart } from '@/api/goods'
import { getLatest, getTotal } from '@/api/order/evaluate'
import { storeInfo } from '@/api'
import { getFriendShareScene } from '@/api/goods/share'
import { updateViewLog, updateShareLog } from '@/api/distribution'
import { getGoodsDistribution, checkIsCouldDistribution, } from '@/api/goods/distribution'
import { AtButton, AtNoticebar, AtRate, AtFloatLayout, AtModal, AtModalAction, AtModalHeader } from 'taro-ui'
import map from '@/utils/map'
import classnames from 'classnames'
import Iconfont from '@/components/Iconfont'
import CarInfo from '@/components/CarInfo'
import Sku from '@/components/Sku'
import { connect } from 'react-redux'
import { updateStore } from '@/store/location/action'
import { goToLogin } from '@/utils/login'
import SkeletonView from './skeleton'
import MediaView from './media'
import './index.scss'

interface State {
  details: any
  skuVisible: boolean
  selectSku: any
  carInfo: ICar
  selectNumber: number
  loaded: boolean
  store: object,
  selectSkuGoods: any
  isSingleSku: boolean
  evaluate: any
  evaluateLen: string | number
  distribution: any
  showGeneralizeInfo: boolean
  selectStore: object
  isSingle: boolean,
  jihuasuanId: string | number
  pMobile: string | number
  ppMobile: string | number
  jihuasuanGoodsId: string | number
  jihuasuanSource: string
  jihuasuanStoreCode: string
  tips: boolean
}

@connect<any>(({ car, location, user }) => ({ car, location, user }), _dispatch => ({
  dispatchStore(params) {
    return _dispatch(updateStore(params))
  }
}))
export default class Index extends Component<any> {
  $instance = getCurrentInstance();
  protected __data__: any
  constructor (props) {
    super(...arguments)
    const {
      currentCar
    } = props.car
    this.state = {
      tips: false,
      details: null,// 商品详情信息
      skuVisible: false,// 是否显示购买详细信息
      selectSku: [],// 选择的sku商品
      carInfo: currentCar,
      selectNumber: 1,
      loaded: false,// 读取商品详情信息接口,是否显示骨架屏
      store: {}, // 带进来的门店信息
      selectSkuGoods: {},
      isSingleSku: false,// 是否为单商品sku
      evaluate: [],// 最新一条评价
      evaluateLen: 0,// 评价总条数
      distribution: null,
      showGeneralizeInfo: false,
      selectStore: {},
      isSingle: true
    }
    this.__data__ = process.env.TARO_ENV === 'weapp' ? '__data__' : 'data'
  }

  state: State

  UNSAFE_componentWillMount() { }
  UNSAFE_componentWillUpdate() {

  }
  async componentDidMount() {
    console.log('componentDidMount')
    let {
      storeCode = '',
      scene,
      goodsDistributionId,
      jihuasuanId,
      pMobile,
      id,
      ppMobile,
      jihuasuanGoodsId,
      jihuasuanSource,
    } = this.$instance.router.params
    console.log('this.$instance.router.params', this.$instance.router.params)
    let storageStoreCode = Taro.getStorageSync('STORECODE') || ''
    console.log('storageStoreCode', storageStoreCode)
    console.log('storeCode', storeCode)
    // console.log(this.$router)
    // 如果存在分销信息 存到本地数据 首页获取附件分销门店要用
    if (jihuasuanId) { // 集划算逻辑
      // 调取浏览接口
      this.updateViewLog()
      this.setState({
        jihuasuanId,
        pMobile,
        ppMobile,
        jihuasuanGoodsId,
        jihuasuanSource,
      })
    }
    if (goodsDistributionId) {
      Taro.setStorageSync('GOODS_DISTRIBUTION_ID', goodsDistributionId)
    }
    this.initdistributionInfo()
    // const { store } = this.state
    // 没有门店信息但是有场景值直接根据场景获取数据
    if (!storeCode && scene) {
      let urlParams = decodeURIComponent(scene).split('_')
      if (urlParams.length > 2) {
        storeCode = urlParams[2]
      }
    }
    let locationData = Taro.getStorageSync('CURRENT_LONGITUDE_LATITUDE')
    if (storeCode && storeCode != 'undefined' && storeCode != '1001R011') {
      let storeParams: any = {
        storeCode,
        inHandleError: true,
      }
      if (locationData) {
        const { latitude: userLatitude, longitude: userLongitude } = locationData
        locationData
        storeParams = {
          ...storeParams,
          userLongitude,
          userLatitude
        }
      } else {
        if (process.env.TARO_ENV === 'weapp') {
          const curLocation: any = await map.getLocation()
          if (curLocation) {
            const { latitude: userLatitude, longitude: userLongitude } = curLocation
            storeParams = {
              ...storeParams,
              userLongitude,
              userLatitude
            }
          }
        }
      }
      storeInfo(storeParams).then(result => {
        const data = result.data['data']
        console.log('data门店的数据', data)
        if (jihuasuanId) { // 集划算活动，需要判断传递进来的门店是否参与活动
          getJihuasuanStoreCanOrder({
            goodsIds: id,
            jihuasuanId,
            jihuasuanSource,
            storeCode,
            type: 1
          }).then(resp => {
            if (resp.data.data.can == 1) {
              this.setState({
                selectStore: data,
              })
            }
            console.log('res', resp)
          })
        } else {
          this.setState({
            selectStore: data,
          })
        }

      })

    } else if (storageStoreCode) {
      console.log('inner--storageStoreCode', storageStoreCode)
      let storeParams: any = {
        storeCode: storageStoreCode,
        ifHandleError: false,
      }
      if (locationData) {
        const { latitude: userLatitude, longitude: userLongitude } = locationData
        locationData
        storeParams = {
          ...storeParams,
          userLongitude,
          userLatitude
        }
      } else {
        if (process.env.TARO_ENV === 'weapp') {
          const curLocation: any = await map.getLocation()
          if (curLocation) {
            const { latitude: userLatitude, longitude: userLongitude } = curLocation
            storeParams = {
              ...storeParams,
              userLongitude,
              userLatitude
            }
          }
        }
      }
      console.log('有没有进来这里-------------+++++++++')
      storeInfo(storeParams).then(result => {
        const data = result.data['data']
        let CURRENT_LOCATION_INFO = Taro.getStorageSync('CURRENT_LOCATION_INFO')
        if (data.cityCode == CURRENT_LOCATION_INFO.adCode) { // 同个地区才选中,集划算的除外
          if (jihuasuanId) {
            console.log('getJihuasuanStoreCanOrder')
            getJihuasuanStoreCanOrder({
              goodsIds: id,
              jihuasuanId,
              jihuasuanSource,
              storeCode: storeParams.storeCode,
              type: 1
            }).then(resp => {
              console.log('getJihuasuanStoreCanOrder-resp', resp.data.data.can)
              if (resp.data.data.can == 1) {
                this.setState({
                  selectStore: data,
                })
              }
              console.log('resp', resp)
            })
          } else {
            this.setState({
              selectStore: data,
            })
          }
          console.log('data门店的数据', data)
        }
      }).catch(err => {
        Taro.setStorageSync('STORECODE', '')
        console.log(err)
      })
    }
    await Promise.all([this.getPlatformGoodsDetails(), this.getEvaluateLatest(), this.getEvaluateTotal()])
  }

  // 选择门店
  selectStores() {
    let { id, cityCode } = this.$instance.router.params
    let {
      details,
      selectStore,
      jihuasuanId,
      jihuasuanSource,
    } = this.state

    let store = details.defaultStore == null ? (selectStore ? selectStore : {}) : details.defaultStore
    if (cityCode) {
      Taro.navigateTo({
        url: `/pages/store/platform/index?goodsIds=${id}&store=${store}&cityCode=${cityCode}&areaCode=''`
      })
    } else if (store.cityCode) {
      Taro.navigateTo({
        url: `/pages/store/platform/index?goodsIds=${id}&store=${store}&cityCode=${store.cityCode}&areaCode=''`
      })
    } else if (jihuasuanId) {
      Taro.navigateTo({
        url: `/pages/store/platform/index?goodsIds=${id}&store=${store}&jihuasuanId=${jihuasuanId}&jihuasuanSource=${jihuasuanSource}`
      })
    } else {
      Taro.navigateTo({
        url: `/pages/store/platform/index?goodsIds=${id}&store=${store}`
      })
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const {
      currentCar
    } = nextProps.car.carInfo
    if (currentCar) {
      if (!this.state.carInfo) {
        this.setState({
          carInfo: currentCar
        })
      } else {
        if (this.state.carInfo.id !== currentCar.id) {
          this.setState({
            carInfo: currentCar
          })
        }
      }
    }
  }

  componentWillUnmount() { }

  async componentDidShow() {
    console.log('componentDidShow')
    let { jihuasuanId } = this.$instance.router.params
    console.log('this.$instance.router.params', this.$instance.router.params)
    let pages = Taro.getCurrentPages();
    console.log('pages----Taro.getCurrentPages()', pages)
    let currentPage = pages[pages.length - 1]; // 获取当前页面
    if (currentPage[this.__data__].selectStore) { // 获取值
      let { selectStore } = this.state
      let flat = true
      if (selectStore.storeCode == currentPage[this.__data__].selectStore.storeCode) {
        flat = false
      }
      // 选择具体门店的时候，价格可能发生了变化,但是两次切换同一家门店的时候，不提示
      this.setState({ selectStore: currentPage[this.__data__].selectStore }, async () => {
        await this.getPlatformGoodsDetails()
        if (flat && !jihuasuanId) { // 如果是集划算的话，都是统一的商品，不用提示。
          Taro.showToast({
            title: '门店已变更，商品价格可能变化！',
            icon: 'none',
            duration: 2000,
          })
        }

      })
    }
    let RESET_STORT = Taro.getStorageSync('RESET_STORT')
    let STORE_LOCATION = Taro.getStorageSync('STORE_LOCATION')
    let distribution = this.state.distribution
    let _this = this
    if (RESET_STORT && distribution) {
      this.setState({
        store: STORE_LOCATION,
      }, () => {
        this.props.dispatchStore(STORE_LOCATION)
        distribution.storeCode = _this.state.store.storeCode || ''
        // 重新选择门店时 需要判断门店是为分销门店
        _this.checkIsCouldDistribution({ storeCode: distribution.storeCode, goodsDistributionId: distribution.goodsDistributionId }).then(res => {
          let checkIsCouldDistribution = true
          // console.log('2')
          if (res && res.data && res.data.success && res.data.data.isDistribution === true) {
            distribution.isDistribution = '1'
          } else {
            checkIsCouldDistribution = false
          }
          _this.setState({ distribution: distribution }, () => {
            if (checkIsCouldDistribution === false) {
              Taro.showToast({
                title: '当前门店不参与分享活动，请重新选择门店',
                icon: 'none',
                duration: 2000,
                success: () => {
                  setTimeout(() => {
                    this.selectStores()
                  }, 500)
                }
              })
            }
          })
          Taro.setStorageSync('RESET_STORT', false)
        })
      })
    }
  }

  componentDidHide() { }
  onShareAppMessage() {
    const {
      id,
      shareType,
      mobile,
      goodsDistributionId,
      storeCode,
      jihuasuanId,
      pMobile,
      ppMobile,
      jihuasuanGoodsId,
      jihuasuanSource,
    } = this.$instance.router.params
    let IS_USERINFO = Taro.getStorageSync('IS_USERINFO')
    let currentMobile = IS_USERINFO.mobile
    const { details, store } = this.state
    let data = {}
    if (store && store.storeName) {
      data = {
        title: `${details.goodsName}-${store.storeName}`,
        path: `/pages/goods/details/index?id=${id}&storeCode=${store.storeCode}${currentMobile ? `&mobile=${currentMobile}&registerType=5` : '&registerType=1'}` //注册方式：有登录分享的为’分享注册（用户分享）’，没有登录分享为’自主注册’
      }
    }
    else if (shareType && goodsDistributionId) {
      // 分享时存在分销参数 需携带
      data = {
        title: `${details.goodsName}`,
        path: `/pages/goods/details/index?id=${id}&storeCode=${storeCode}&shareType=1&mobile=${mobile}&goodsDistributionId=${goodsDistributionId}`
      }
    } else if (jihuasuanId) {
      // 集划算分享接口
      this.updateShareLog()
      data = {
        title: `${details.goodsName}`,
        path: `/pages/goods/details/index?id=${id}&jihuasuanId=${jihuasuanId}&pMobile=${currentMobile}&ppMobile=${pMobile}&jihuasuanGoodsId=${jihuasuanGoodsId}&jihuasuanSource=0`
      }
    }
    else {
      data = {
        title: `${details.goodsName}`,
        path: `/pages/goods/details/index?id=${id}${currentMobile ? `&mobile=${currentMobile}&registerType=5` : '&registerType=1'}` //注册方式：有登录分享的为’分享注册（用户分享）’，没有登录分享为’自主注册’
      }
    }
    console.log('分享数据----data', data)
    return data
  }
  // 集划算浏览接口
  updateViewLog() {
    let IS_USERINFO = Taro.getStorageSync('IS_USERINFO')
    let { jihuasuanId, pMobile, ppMobile, jihuasuanGoodsId, jihuasuanSource } = this.$instance.router.params
    let mobile = IS_USERINFO.mobile
    let params = {
      mobile,
      jihuasuanId,
      pMobile,
      ppMobile,
      jihuasuanGoodsId,
      source: jihuasuanSource
    }
    updateViewLog(params).then(res => {
      console.log('updateViewLog', res)
    }).catch((err) => {
      console.log('err', err)
    })
  }

  // 集划算分享接口
  updateShareLog() {
    let IS_USERINFO = Taro.getStorageSync('IS_USERINFO')
    let { jihuasuanId, pMobile, ppMobile, jihuasuanGoodsId, jihuasuanSource } = this.$instance.router.params
    let mobile = IS_USERINFO.mobile
    let params = {
      mobile,
      jihuasuanId,
      pMobile,
      ppMobile,
      jihuasuanGoodsId,
      source: jihuasuanSource
    }
    updateShareLog(params).then(res => {
      console.log('updateShareLog', res)
    }).catch((err) => {
      console.log('err', err)
    })
  }

  setTips = () => {
    let { details } = this.state
    if (details.canBuy == 0 || details.isDeleted == 1) {
      this.setState({
        tips: true
      })
    } else {
      this.setState({
        tips: false
      })
    }

  }

  // 商品详情信息
  async getPlatformGoodsDetails() {
    console.log('getPlatformGoodsDetails---getPlatformGoodsDetails')
    let { id, storeCode = '', scene, jihuasuanId, jihuasuanGoodsId, jihuasuanSource } = this.$instance.router.params
    let urlParams = decodeURIComponent(scene).split('_')
    if (!id) {
      id = urlParams[1]
    }

    const { carInfo } = this.state
    let params: any = {
      goodsId: id
    }
    if (carInfo) {
      params = {
        ...params,
        carLicense: carInfo.carLicense
      }
    }
    if (storeCode) {
      params = {
        ...params,
        storeCode
      }
    }
    if (jihuasuanId) {
      params = {
        ...params,
        jihuasuanId,
        jihuasuanGoodsId
      }
    }
    console.log('getPlatformGoodsDetails----params', params)
    const goodsResult = await getPlatformGoodsDetails(params)
    const data = {
      ...goodsResult.data['data'],
      introduce: goodsResult.data['data'].introduce.replace(/^\s+|\s+$/g, '').split(/\n/).map(v => v.replace(/^\s+|\s+$/g, '')),
    }
    data.imageInfo.promotion = data.promotion ? data.promotion : []
    let { selectStore } = this.state
    console.log('selectStore---selectStore', selectStore)
    console.log('有么有执行进来这里', jihuasuanId)
    let locationData = Taro.getStorageSync('CURRENT_LONGITUDE_LATITUDE')

    if (!selectStore.storeCode && data.defaultStore) {
      console.log('执行了没有---------data.defaultStore', data.defaultStore)
      storeInfo({
        storeCode: data.defaultStore.storeCode,
        userLatitude: locationData.latitude || '',
        userLongitude: locationData.longitude || '',
        ifHandleError: false,
      }).then(result => {
        const storeData = result.data['data']
        console.log('storeData', storeData)
        if (jihuasuanId) {
          getJihuasuanStoreCanOrder({
            goodsIds: id,
            jihuasuanId,
            jihuasuanSource,
            storeCode: storeData.storeCode,
            type: 1
          }).then(resp => {
            if (resp.data.data.can == 1) {
              console.log('storeData---storeData', storeData)
              this.setState({
                details: data,
                selectStore: storeData
              }, async () => {
                this.setTips()
                // 如果商品sku只有一个，默认选中
                await this.getSkuInfo(data)
                this.setState({
                  loaded: true
                })
              })
            } else {
              this.setState({
                details: data,
              }, async () => {
                this.setTips()
                // 如果商品sku只有一个，默认选中
                await this.getSkuInfo(data)
                this.setState({
                  loaded: true
                })
              })
            }

            console.log('res', resp)
          })
        } else {
          this.setState({
            details: data,
            selectStore: storeData
          }, async () => {
            this.setTips()
            // 如果商品sku只有一个，默认选中
            await this.getSkuInfo(data)
            this.setState({
              loaded: true
            })
          })
        }
      }).catch(err => {
        console.log(err)
      })
    } else {
      this.setState({
        details: data,
      }, async () => {
        this.setTips()
        // 如果商品sku只有一个，默认选中
        await this.getSkuInfo(data)
        this.setState({
          loaded: true
        })
      })
    }

  }

  // 单商品默认sku
  getSkuInfo(data) {
    let { jihuasuanGoodsId, jihuasuanId } = this.$instance.router.params
    // 如果商品sku只有一个，默认选中,调整为，无论是不是多sku还是单sku，默认选择第一个
    let { selectStore } = this.state
    console.log('getSkuInfo----getSkuInfo', selectStore)
    // if (Array.isArray(data.skuInfo) && data.skuInfo.length == 1 && data.skuInfo[0].items.length == 1) {
    const { id, skuInfo } = data
    const { details } = this.state

    const goodsInfo = {
      id: details.id,
      name: details.goodsName,
      stock: details.stock,
      salePrice: details.salePrice,
      thumbUrl: details.imageInfo.thumbnail.url,
      isOnSale: details.isOnSale
    }
    let params = {
      goodsId: id,
      skuItemIds: skuInfo[0].items[0].id,
    }
    if (jihuasuanId) {
      params.jihuasuanId = jihuasuanId
      params.jihuasuanGoodsId = jihuasuanGoodsId
    }
    if (selectStore && selectStore.storeCode) {
      params.storeCode = selectStore.storeCode
    }
    getSkuInfo(params).then(res => {
      const data = res.data['data']
      const selectSku = [{
        id: details.skuInfo[0].id,
        name: details.skuInfo[0].name,
        property: details.skuInfo[0].items[0]
      }]

      this.setState({
        isSingleSku: true,
        isSingle: true,
        selectSku,
        selectSkuGoods: {
          ...goodsInfo,
          stock: data.stock,
          stockTips: data.stockTips,
          thumbUrl: data.thumbUrl,
          salePrice: data.salePrice,
          goodsSkuId: data.goodsSkuId,
          originalPrice: data.originalPrice
        },
      })
    }).catch((err) => {
      let { details } = this.state
      details.defaultStore = null
      this.setState({
        details,
        selectStore: {}
      })
      console.log('err', err)
    })
    // }
    // else if(Array.isArray(data.skuInfo) && data.skuInfo.length > 1){ // 多商品，多sku 或者单sku，默认选中第一个sku
    // 	const { id, skuInfo } = data
    //   const { details } = this.state

    //   const goodsInfo = {
    //     id: details.id,
    //     name: details.goodsName,
    //     stock: details.stock,
    //     salePrice: details.salePrice,
    //     thumbUrl: details.imageInfo.thumbnail.url,
    //     isOnSale: details.isOnSale
    //   }
    // 	let skuItemIds = []
    // 	skuInfo.map(item=>{
    // 		skuItemIds.push(item.items[0].id)
    // 	})
    // 	let params = {
    // 		goodsId: id,
    //     skuItemIds: skuItemIds.join(',')
    // 	}
    // 	if(selectStore && selectStore.storeCode){
    // 		params.storeCode = selectStore.storeCode
    // 	}
    // 	let skudata = []
    // 	details.skuInfo.map(v=>{
    // 		skudata.push({
    // 			id: v.id,
    //       name: v.name,
    //       property: v.items[0]
    // 		})
    // 	})
    //   getSkuInfo(params).then(res => {
    //     const data = res.data['data']
    //     this.setState({
    // 			isSingle:false,
    //       isSingleSku: true,
    //       selectSku:skudata,
    //       selectSkuGoods: {
    //         ...goodsInfo,
    //         stock: data.stock,
    //         stockTips: data.stockTips,
    //         thumbUrl: data.thumbUrl,
    //         salePrice: data.salePrice,
    //         goodsSkuId: data.goodsSkuId,
    //         originalPrice: data.originalPrice
    //       },
    //     })
    //   }).catch((err)=>{
    // 		console.log('err',err)
    // 		let { details } = this.state
    // 		details.defaultStore = null
    // 		this.setState({
    // 			details,
    // 			selectStore:{}
    // 		})
    // 	})
    // }
  }

  // 最新一条评价
  async getEvaluateLatest() {
    const { id } = this.$instance.router.params
    try {
      const res = await getLatest({
        goodsId: id
      })
      let { data } = res.data
      // console.log('data', data)
      this.setState({
        evaluate: data instanceof Array ? [] : [data]
      })
    } catch (error) {
      console.log(error)
    }
  }

  // 评价总条数
  async getEvaluateTotal() {
    const { id } = this.$instance.router.params
    try {
      const res = await getTotal({
        goodsId: id
      })
      this.setState({
        evaluateLen: res.data.data.total
      })
    } catch (error) {
      console.log(error)
    }
  }

  // 获取商品分销信息
  async getGoodsDistribution(data) {
    try {
      const res = await getGoodsDistribution(data)
      return res
    } catch (error) {
      console.log(error)
    }
  }

  // 判断门店是否参与商品分销
  async checkIsCouldDistribution(data) {
    try {
      const res = await checkIsCouldDistribution(data)
      return res
    } catch (error) {
      console.log(error)
    }
  }

  // 商品标题、价格
  goodsInfo() {
    const {
      details,
      selectSku,
      selectSkuGoods
    } = this.state
    // console.log(selectSku,'***')
    return (
      <View className="goods-details-box">
        {
          selectSku.length > 0 ? <View className='goods-details-price'>
            <View className='goods-details-price-bold'>{`￥${Number(selectSkuGoods.salePrice)}`}</View>
            <AtButton className='goods-details-share' openType='share' size='small' type='secondary'>
              <Iconfont size='34' color='#999' name='icon-fenxiang' />分享
            </AtButton>
          </View> : <View className='goods-details-price'>
            {/*
						*/}
            {
              details.minPrice == details.maxPrice ? <View className='goods-details-price-bold'>{`￥${Number(details.originalPrice)}`}</View> :
                <View className='goods-details-price-bold mini'>{`￥${Number(details.minPrice)}`}~{`￥${Number(details.maxPrice)}`}</View>
            }
            <AtButton className='goods-details-share' openType='share' size='small' type='secondary'>
              <Iconfont size='34' color='#999' name='icon-fenxiang' />分享
            </AtButton>
          </View>
        }
        <View className='goods-details-title'>{details.goodsName}</View>
        {/* 商品描述 */}
        <View className='goods-details-description'>{details.description}</View>
        {/* 质保 */}
        {
          details.warranty && <View className='goods-details-warranty'>{details.warranty}</View>
        }
        {/*
				 */}
      </View>
    )
  }

  // 分销信息初始化
  initdistributionInfo() {
    let { isDistribution, scene } = this.$instance.router.params
    // 存在分销扫码参数 数据从接口获取
    if (scene) {
      let params = decodeURIComponent(scene).split('_')
      let distribution = params[0]
      if (distribution) {
        this.getFriendShareScene({ disShareId: distribution }).then((res) => {
          if (res && res.data.success) {
            let apiDistribution = JSON.parse(res.data.data.text)
            let { storeCode, goodsDistributionId, id, isDistribution, mobile, mobile2, shareType, isStaff } = apiDistribution
            // 需要判断门店是为分销门店
            this.checkIsCouldDistribution({ storeCode: storeCode, goodsDistributionId: goodsDistributionId }).then(res => {
              // console.log('3')
              if (res && res.data && res.data.success && res.data.data.isDistribution === true) {
                isDistribution = '1'
              } else {
                isDistribution = '-1'
              }
              // 设置分销信息
              if (isDistribution === '1' && goodsDistributionId) {
                if (mobile !== "" && mobile2 !== "") {
                  isDistribution = '-1'
                }
                // 获取商品分销信息
                this.getGoodsDistribution({ id: goodsDistributionId, storeCode }).then((res) => {
                  if (res && res.data.success === true) {
                    this.setState({
                      distribution: {
                        storeCode, goodsDistributionId, id, isDistribution, mobile, mobile2, shareType, isStaff,
                        directlyCommissionPrice: res.data.data.directlyCommissionPrice,
                        indirectCommissionPrice: res.data.data.indirectCommissionPrice,
                        reductionPriceNumber: res.data.data.reductionPriceNumber,
                        urlStoreCode: storeCode,
                        text: res.data.data.text
                      }
                    })
                  }
                })
              }
            })
          }
        })
      }
    } else if (isDistribution) {
      let { storeCode, goodsDistributionId, id, isDistribution, mobile, mobile2, shareType, isStaff } = this.$instance.router.params
      const localStoreCode = Taro.getStorageSync('STORECODE')
      // Url没有存在storeCode 默认使用本地localStoreCode
      if (!storeCode && localStoreCode) {
        storeCode = localStoreCode
      }
      // 需要判断门店是为分销门店
      this.checkIsCouldDistribution({ storeCode: storeCode, goodsDistributionId: goodsDistributionId }).then(res => {
        let checkIsCouldDistribution = true
        if (res && res.data && res.data.success && res.data.data.isDistribution === true) {
          isDistribution = '1'
        } else {
          checkIsCouldDistribution = false
        }
        // 设置分销信息
        if (isDistribution === '1' && goodsDistributionId) {
          // 获取商品分销信息
          this.getGoodsDistribution({ id: goodsDistributionId, storeCode }).then((res) => {
            if (res && res.data.success === true) {
              if (mobile !== "" && mobile2 !== "") {
                isDistribution = '-1'
              }
              this.setState({
                distribution: {
                  storeCode, goodsDistributionId, id, isDistribution, mobile, mobile2, shareType, isStaff,
                  urlStoreCode: storeCode,
                  directlyCommissionPrice: res.data.data.directlyCommissionPrice,
                  indirectCommissionPrice: res.data.data.indirectCommissionPrice,
                  reductionPriceNumber: res.data.data.reductionPriceNumber,
                  text: res.data.data.text
                }
              }, () => {
                if (checkIsCouldDistribution === false) {
                  // console.log('重新选择门店1')
                  this.selectStores()
                }
              })
            }
          })
        }
      })
    }
  }

  // 获取朋友圈分销信息
  async getFriendShareScene(data) {
    try {
      const res = await getFriendShareScene(data)
      return res
    } catch (error) {
      console.log(error)
    }
  }

  // 推广奖励
  generalize() {
    const { distribution } = this.state
    return (
      <View className='goods-details-sku' onClick={() => {
        this.setState({
          showGeneralizeInfo: true
        })
      }}
      >
        <View className='goods-details-text'>
          <View className='goods-details-text-lable'>推广奖励</View>
          <View className='goods-details-text-sku'>
            ( 直接￥{distribution && distribution.directlyCommissionPrice} 间接￥{distribution && distribution.indirectCommissionPrice} ){ }
          </View>
        </View>
        <View className='goods-details-sku-icon'>
          <Iconfont size='26' color='#ccc' name='icon-jiantourukou' />
        </View>
      </View>
    )
  }

  // 推广详情
  generalizeInfo() {
    const { showGeneralizeInfo, distribution } = this.state
    return (
      <AtFloatLayout className="generalize-info"
        isOpened={showGeneralizeInfo === true}
        onClose={() => {
          this.setState({ showGeneralizeInfo: false })
        }} title="推广奖励佣金说明" >
        <View className="block">
          <View className="money-block">
            <Text className="money-block-text">直接奖励</Text><Text>￥{distribution && distribution.directlyCommissionPrice}</Text>
          </View>
          <View className="money-block">
            <Text className="money-block-text">间接奖励</Text><Text>￥{distribution && distribution.indirectCommissionPrice}</Text>
          </View>
        </View>
        <View className="title">普通奖励:</View>
        <View className="explain">普通用户通过你分享的链接购买商品，你可获得直接奖励。</View>
        <View className="title">间接奖励:</View>
        <View className="explain">普通用户通过你的队友购买商品，你可获得间接奖励。</View>
      </AtFloatLayout>)
  }

  // sku
  skuInfo() {
    const {
      selectSku,
      details
    } = this.state
    return (
      <View style={{ 'position': 'relative' }} className='goods-details-sku' onClick={() => {
        this.setState({
          skuVisible: true
        })
      }}
      >
        <View className='goods-details-text'>
          <View className='goods-details-text-lable'>{selectSku.length ? '已选择' : '请选择'}</View>
          <View className='goods-details-text-sku'>
            {
              selectSku.length > 0 ? (
                selectSku.map((v, i) => {
                  return (
                    <Text key={v.id}>
                      {
                        selectSku.length - 1 !== i ? v.property.name + ',' : v.property.name
                      }
                    </Text>
                  )
                })
              ) : details.skuInfo.map((v, i) => {
                return (
                  <Text key={v.id}>
                    {
                      details.skuInfo.length - 1 !== i ? v.name + ' ' : v.name
                    }
                  </Text>
                )
              })
            }
          </View>
        </View>
        <View className='goods-details-sku-icon'>
          <Iconfont size='26' color='#ccc' name='icon-jiantourukou' />
        </View>
      </View>
    )
  }

  // 承诺
  promiseInfo() {
    const {
      details
    } = this.state

    return details.promiseInfo.length > 0 && (
      <View className='goods-details-blockview goods-details-promise'>
        {
          details.promiseInfo.map((promise, promiseIdx) => {
            return (
              <View key={promiseIdx} className='goods-details-promise-li'>{promise.name}</View>
            )
          })
        }
      </View>
    )
  }

  //预览评价图片
  previewImage(current, urls) {
    Taro.previewImage({
      current, // 当前显示图片的http链接
      urls, // 需要预览的图片http链接列表
    })
  }

  // 商品评价
  evaluateView() {
    const {
      evaluate,
      evaluateLen
    } = this.state
    const { id } = this.$instance.router.params
    return evaluate.length > 0 && (
      <View className='goods-details-blockview'>

        <View className='goods-details-evaluate'>
          <View className='goods-details-evaluate-head'>
            <View className="l">
              <Text className='title'>商品评价</Text>
              <Text className='total'>({evaluateLen}条）</Text>
            </View>
            <View className="r" onClick={() => {
              Taro.navigateTo({ url: `/pages/evaluate/list/index?id=${id}` })
            }}>
              <Text>查看更多</Text>
              <Iconfont size='26' color='#ccc' name='icon-jiantourukou' />
            </View>
          </View>
          <View className='goods-details-evaluate-cont'>
            {
              evaluate.map((evalItem, evaluateIdx) => {
                return (
                  <View key={String(evalItem.goodsId)} className='goods-details-evaluate-cont-li'>
                    <View className='head'>
                      <View className='head-top'>
                        <View className='left'>
                          <View className='left-wrap'>
                            <Image className='brand-img' mode='aspectFill' src={evalItem.brandLogo} lazyLoad />
                            <Text className='car-license'>{evalItem.carLicense}</Text>
                          </View>
                          <Text className='brand-name'>{evalItem.carSeriesName}</Text>
                        </View>

                        <Text className='date'>{evalItem.commentDate}</Text>
                      </View>
                      <View className='head-bottom'>
                        <Text className='range-text'>评分:</Text>
                        <AtRate size={15} value={evalItem.goodsGrade} />
                      </View>
                    </View>
                    <View className='content'>
                      <View className='content-desc'>
                        {evalItem.commentContent}
                      </View>
                      {
                        evalItem.coverImgUrl && evalItem.coverImgUrl.length > 0 &&
                        <View className='content-pics'>
                          {evalItem.coverImgUrl.map((url) => <Image className='img' mode='aspectFill' src={url} lazyLoad onClick={() => this.previewImage(url, evalItem.coverImgUrl)} />)}
                        </View>
                      }
                    </View>
                  </View>
                )
              })
            }
          </View>
        </View>
      </View>
    )
  }

  // 商品介绍
  introduce() {
    const {
      details
    } = this.state
    return details.introduce && (
      <View className='goods-details-blockview'>
        <View className='goods-details-info'>商品介绍</View>
        <View className='goods-details-info-wrap'>
          {
            details.introduce.map((introduce, introduceIdx) => {
              return (
                <View key={introduceIdx} className='goods-details-info-li'>
                  <View className='goods-details-info-li-cont'>{introduce}</View>
                </View>
              )
            })
          }
        </View>
      </View>
    )
  }

  // 商品图片详情
  goodsMsg() {
    const {
      details
    } = this.state
    return (
      <View className='goods-details-blockview'>
        {
          details.imageInfo.desc.map((desc, descIndex) => {
            return (
              <Image mode='widthFix' lazyLoad className='goods-details-descimg' src={desc.url} key={descIndex} />
            )
          })
        }
      </View>
    )
  }
  // 去分享
  goShare = () => {
    const { distribution = {} } = this.state
    let tempData = JSON.parse(JSON.stringify(distribution))
    let IS_USERINFO = Taro.getStorageSync('IS_USERINFO')
    // 判断参数url参数是否有用户手机 没有默认获取当前登录用户
    if (IS_USERINFO.mobile && tempData && tempData.mobile === '') {
      tempData.mobile1 = IS_USERINFO.mobile
    }

    Taro.navigateTo({ url: '/pages/goods/share/index?distribution=' + JSON.stringify(tempData) })
  }

  btFixed() {
    const { details, selectSkuGoods, distribution } = this.state
    let mobile = this.$instance.router.params.mobile
    let mobile2 = this.$instance.router.params.mobile2
    let { jihuasuanId } = this.$instance.router.params

    return (
      <View className='goods-details-btfixed-wrap'>
        {
          details.isOnSale === 0 ? <AtNoticebar icon='alert-circle'>商品已下架，可以<Text className='blue' onClick={() => Taro.switchTab({ url: '/pages/tabbar/category/index' })}>可以看看其他商品</Text></AtNoticebar> : ''
          // (details.match_tips ? <AtNoticebar icon='alert-circle'>{details.match_tips}</AtNoticebar> : store && store.distance > 30 && <AtNoticebar icon='alert-circle'>您当前位置距离门店较远，请确认位置或<Text className='blue' onClick={() => Taro.navigateTo({ url: '/pages/store/index/index' })}>查看常用门店</Text></AtNoticebar>)
        }
        <View className='goods-details-btfixed'>
          <View className='goods-details-btfixed-icon'>
            <View className='goods-details-btfixed-btnitem-li' onClick={() => {
              Taro.switchTab({
                url: '/pages/tabbar/index/index'
              })
            }}
            >
              <Iconfont size='44' color='#999' name='icon-zu' />
              <View>首页</View>
            </View>

            {
              distribution != null && distribution.isDistribution === '1' ? '' :
                <View className='goods-details-btfixed-btnitem-li' onClick={() => {
                  Taro.switchTab({
                    url: '/pages/tabbar/cart/index'
                  })
                }}
                >
                  <Iconfont size='44' color='#999' name='icon-zu3' />
                  <View>购物车</View>
                </View>
            }
          </View>
          {
            distribution != null && distribution.isDistribution === '1' && (distribution.mobile === '' || distribution.mobile2 === '' || mobile === '' || mobile2 === '') ?
              <View>
                {
                  details.isOnSale === 1 ?
                    <View className='goods-details-btfixed-btnitem'>
                      <View className={classnames('goods-details-btfixed-btn', selectSkuGoods.stock == 0 && 'gray')} onClick={(e) => this.nextHandle(1, e)}>
                        <View className="distribution-btn"> <View>自购省钱</View><View className="small-font">减￥{distribution.reductionPriceNumber}</View> </View>
                      </View>
                      <View className={classnames('goods-details-btfixed-btn', selectSkuGoods.stock == 0 && 'gray')} onClick={this.goShare}>
                        <View className="distribution-btn"> <View>推广赚钱</View><View className="small-font" >赚￥{distribution.directlyCommissionPrice}</View> </View>
                      </View>
                    </View> :
                    <View className='goods-details-btfixed-btnitem disabled'>
                      <View className='goods-details-btfixed-btn gray'>已下架</View>
                    </View>
                }
              </View> :
              <View className='es-box'>
                {
                  details.isOnSale === 1 ?
                    <View className='goods-details-btfixed-btnitem'>
                      {
                        !jihuasuanId ? <View className={classnames('goods-details-btfixed-btn', selectSkuGoods.stock == 0 && 'gray')} onClick={(e) => this.nextHandle(0, e)}>加入购物车</View> : null
                      }
                      <View className={classnames('goods-details-btfixed-btn', jihuasuanId && 'cheap-btn', selectSkuGoods.stock == 0 && 'gray')} onClick={(e) => this.nextHandle(1, e)}>立即购买</View>
                    </View> :
                    <View className='goods-details-btfixed-btnitem disabled'>
                      <View className='goods-details-btfixed-btn gray'>已下架</View>
                    </View>
                }
              </View>
          }
        </View>
      </View>
    )
  }
  /**
   * 查看更多活动
  * **/
  handleUser() {
    Taro.navigateTo({ url: `/pages/webview/index/index?path=${'/cheap/user'}` })
  }
  closeSkuhandle(select, number, selectSkuGoods) {
    this.setState({
      selectSkuGoods,
      skuVisible: false,
      selectSku: select,
      selectNumber: number
    })
  }
  private addStatus: boolean = false
  // 立即购买/加入购物车
  nextHandle(directBuy, e) {
    if (this.addStatus) return
    this.addStatus = true
    const {
      selectSku,
      details,
      selectNumber,
      selectSkuGoods,
      selectStore,
      isSingle,
      jihuasuanId = '',
      pMobile = '',
      ppMobile = '',
      jihuasuanGoodsId = '',
      jihuasuanSource = '',
    } = this.state
    console.log('jihuasuanId', jihuasuanId)
    console.log('e', e)
    if (jihuasuanId && directBuy == 0) {
      Taro.showToast({
        title: '当前商品为集划算商品，无法加入购物车。',
        icon: 'none',
        duration: 2000,
      })
      this.addStatus = false
      return
    }
    const { user } = this.props
    if (!user.userInfo.accessId) {
      goToLogin()
      return
    }
    let storeCode = selectStore.storeCode
    if (!selectStore.storeName) {  // 加入购物车的时候需要先选择下单门店
      Taro.showToast({
        title: '请先选择下单门店！',
        icon: 'none',
        duration: 2000,
      })
      this.addStatus = false
      return
    }
    if (selectSku.length > 0) {
      if (!isSingle) {
        this.setState({
          skuVisible: true
        })
        this.addStatus = false
        return
      }

      if (!selectSkuGoods.stock) {
        // Taro.atMessage({
        //   'message': selectSkuGoods.stockTips || '库存空空如也'
        // })
        return
      }
      if (!selectSkuGoods.goodsSkuId) {
        return
      }
      // const skuItemIds = selectSku.filter(v => v && v.property.id).map(v => v.property.id)
      createCart({
        goodsData: JSON.stringify([{
          goodsId: details.id,
          goodsSkuId: selectSkuGoods.goodsSkuId,
          number: selectNumber,
          itemType: 1,
          directBuy
        }]),
        storeCode: storeCode
      }).then(res => {
        const data = res.data.data
        if (!directBuy) {
          Taro.showToast({
            'title': '成功加入购物车'
          })
        } else {
          // address:'', // 分享有礼带过来的门店地址storeName:'',
          let url = `/pages/order/index/index?cartIds=${JSON.stringify(data.cartIds)}`
          if (selectStore.storeCode) {
            url = jihuasuanId ?
              `/pages/order/index/index?cartIds=${JSON.stringify(data.cartIds)}&store=${JSON.stringify(selectStore)}&jihuasuanId=${jihuasuanId}&pMobile=${pMobile}&ppMobile=${ppMobile}&jihuasuanGoodsId=${jihuasuanGoodsId}&jihuasuanSource=${jihuasuanSource}`
              :
              `/pages/order/index/index?cartIds=${JSON.stringify(data.cartIds)}&store=${JSON.stringify(selectStore)}`
          } else if (details.defaultStore && details.defaultStore.storeName) {
            url = jihuasuanId ? `/pages/order/index/index?cartIds=${JSON.stringify(data.cartIds)}&store=${JSON.stringify(details.defaultStore)}&jihuasuanId=${jihuasuanId}&pMobile=${pMobile}&ppMobile=${ppMobile}&jihuasuanGoodsId=${jihuasuanGoodsId}&jihuasuanSource=${jihuasuanSource}`
              :
              `/pages/order/index/index?cartIds=${JSON.stringify(data.cartIds)}&store=${JSON.stringify(details.defaultStore)}`
          }
          if (this.state.distribution) {
            let tempData = JSON.parse(JSON.stringify(this.state.distribution))
            // console.log('立即购买', tempData);
            let IS_USERINFO = Taro.getStorageSync('IS_USERINFO')
            // 判断参数url参数是否有用户手机 没有默认获取当前登录用户
            if (IS_USERINFO.mobile && tempData && tempData.mobile === '') {
              tempData.mobile = IS_USERINFO.mobile
            }
            url += '&distribution=' + JSON.stringify(tempData)
          }
          // 去购买，跳转页面
          //
          console.log('url', url)
          Taro.navigateTo({ url })
        }
        this.addStatus = false
      }).catch(e => {
        this.addStatus = false
      })
    } else {
      this.setState({
        skuVisible: true
      })
      this.addStatus = false
    }
    e.stopPropagation()
  }
  render() {
    const { isDeleted, tips, activityStatus, details, skuVisible, loaded, store, evaluate, distribution, selectSku, selectSkuGoods, isSingleSku, selectStore,
      jihuasuanId = '',
      pMobile = '',
      ppMobile = '',
      jihuasuanGoodsId = '',
      jihuasuanSource = '', } = this.state
    let tempData = JSON.parse(JSON.stringify(this.state.distribution))
    let IS_USERINFO = Taro.getStorageSync('IS_USERINFO')
    let CURRENT_LOCATION_INFO = Taro.getStorageSync('CURRENT_LOCATION_INFO')
    console.log('render----selectStore', selectStore)
    console.log('render----CURRENT_LOCATION_INFO', CURRENT_LOCATION_INFO)
    console.log('CURRENT_LOCATION_INFO.adCode', CURRENT_LOCATION_INFO.adCode)
    console.log('selectStore', selectStore.cityCode)
    // 判断参数url参数是否有用户手机 没有默认获取当前登录用户
    if (IS_USERINFO.mobile && tempData && tempData.mobile === '') {
      tempData.mobile = IS_USERINFO.mobile
    }
    // console.log('立即购买', tempData);
    return loaded ? (
      <View className='goods-details'>
        <View className='goods-details-carinfo'>
          <CarInfo />
        </View>
        <Sku
          onClose={this.closeSkuhandle.bind(this)}
          visible={skuVisible}
          goodsInfo={isSingleSku ? selectSkuGoods : {
            id: details.id,
            name: details.goodsName,
            stock: details.stock,
            salePrice: details.salePrice,
            thumbUrl: details.imageInfo.thumbnail.url,
            isOnSale: details.isOnSale
          }}
          selectStore={selectStore}
          jihuasuanInfo={
            {
              jihuasuanId,
              pMobile,
              ppMobile,
              jihuasuanGoodsId,
              jihuasuanSource
            }
          }
          sku={details.skuInfo}
          distribution={tempData}
          currentSku={selectSku}
          maxNumber={details.maxNumber}
        />
        <View className='goods-details-blockview'>
          <MediaView imageInfo={details.imageInfo} />
          {this.goodsInfo()}
          {this.skuInfo()}
        </View>
        <View className="generalize">
          {
            distribution != null && distribution.isDistribution === '1' ?
              this.generalize() : ''}
        </View>
        {this.promiseInfo()}
        <View className='goods-details-flex-view' onClick={() => { this.selectStores() }}>
          <View className='title'  >
            <View className='span'>服务提供方</View>
            <View className='em'></View>
          </View>

          <View className='distance'>
            <View className='text'>{selectStore.storeName ? selectStore.storeName : (details.defaultStore && !jihuasuanId ? details.defaultStore.storeName : '请选择下单门店')}</View>
            <Iconfont size='26' color='#ccc' name='icon-jiantourukou' />
          </View>
        </View>
        {
          selectStore.address &&
          <View className='goods-details-flex-address'>
            {selectStore.address}
            {
              selectStore.distance ? <Text> | {selectStore.distance}km</Text> : null
            }
          </View>
        }
        {
          jihuasuanId && CURRENT_LOCATION_INFO && selectStore.cityCode && CURRENT_LOCATION_INFO.adCode != selectStore.cityCode ?
            <View className='location-tips-txt'>
              <View>温馨提示：该门店与你所在位置不在同一个城市，</View>
              <View>请仔细确认下单门店。</View>
            </View>
            : null
        }
        {
          jihuasuanId && CURRENT_LOCATION_INFO && selectStore.cityCode && CURRENT_LOCATION_INFO.adCode == selectStore.cityCode && selectStore.distance && selectStore.distance >= 30 ?
            <View className='location-tips-txt'>
              <View>温馨提示：该门店与你所在距离较远，</View>
              <View>请仔细确认下单门店。</View>
            </View>
            : null
        }
        {this.evaluateView()}
        {this.introduce()}
        {this.goodsMsg()}
        {this.btFixed()}
        {this.generalizeInfo()}

        <AtModal isOpened={tips} closeOnClickOverlay={false}>
          <AtModalHeader>很抱歉，你来晚了</AtModalHeader>
          <View className='at-tips'>
            <View>{details.canBuy == 0 ? '活动时间已结束，' : (details.isDeleted == 1 ? '年卡不存在，' : '')}感谢您的支持</View>
            <View>看看其他活动发现更多福利哦！</View>
          </View>
          <AtModalAction>  <Button onClick={this.handleUser}>查看其他活动</Button> </AtModalAction>
        </AtModal>
      </View>
    ) : <SkeletonView />
  }
}
